@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion

:: 物联网车辆管理系统 - 数据库连接测试脚本 (Windows版本)

echo ========================================
echo    物联网车辆管理系统 - 连接测试
echo ========================================
echo.

:: 检查服务是否运行
echo [INFO] 检查服务状态...
docker-compose ps | findstr "Up" >nul 2>&1
if errorlevel 1 (
    echo [ERROR] 服务未启动，请先运行: deploy.bat
    pause
    exit /b 1
)
echo [SUCCESS] 服务正在运行

:: 测试PostgreSQL连接
echo [INFO] 测试 PostgreSQL 连接...
docker-compose exec -T postgres pg_isready -h localhost -p 5432 >nul 2>&1
if errorlevel 1 (
    echo [ERROR] PostgreSQL 连接失败
    set /a failed_tests+=1
) else (
    echo [SUCCESS] PostgreSQL 连接正常
    
    :: 测试数据库查询
    for /f "tokens=*" %%i in ('docker-compose exec -T postgres psql -U bicycle_user -d bicycle -c "SELECT COUNT(*) FROM users;" 2^>nul ^| findstr /r "[0-9]"') do (
        echo [INFO] 用户表包含 %%i 条记录
    )
)

:: 测试Redis连接
echo [INFO] 测试 Redis 连接...
docker-compose exec -T redis redis-cli ping | findstr "PONG" >nul 2>&1
if errorlevel 1 (
    echo [ERROR] Redis 连接失败
    set /a failed_tests+=1
) else (
    echo [SUCCESS] Redis 连接正常
    
    :: 测试Redis读写
    docker-compose exec -T redis redis-cli set test_key "test_value" >nul 2>&1
    for /f "tokens=*" %%i in ('docker-compose exec -T redis redis-cli get test_key 2^>nul') do (
        if "%%i"=="test_value" (
            echo [SUCCESS] Redis 读写操作正常
        ) else (
            echo [ERROR] Redis 读写操作失败
        )
    )
    docker-compose exec -T redis redis-cli del test_key >nul 2>&1
)

:: 测试EMQX连接
echo [INFO] 测试 EMQX 连接...
docker-compose ps emqx | findstr "Up" >nul 2>&1
if errorlevel 1 (
    echo [ERROR] EMQX 容器未运行
    set /a failed_tests+=1
) else (
    echo [SUCCESS] EMQX 容器运行正常
)

:: 测试管理工具端口
echo [INFO] 测试管理工具...
netstat -an | findstr ":8080" >nul 2>&1
if errorlevel 1 (
    echo [WARNING] pgAdmin 端口不可访问
) else (
    echo [SUCCESS] pgAdmin 可访问: http://localhost:8080
)

netstat -an | findstr ":8081" >nul 2>&1
if errorlevel 1 (
    echo [WARNING] Redis Commander 端口不可访问
) else (
    echo [SUCCESS] Redis Commander 可访问: http://localhost:8081
)

netstat -an | findstr ":18083" >nul 2>&1
if errorlevel 1 (
    echo [WARNING] EMQX Dashboard 端口不可访问
) else (
    echo [SUCCESS] EMQX Dashboard 可访问: http://localhost:18083
)

:: 显示容器状态
echo.
echo [INFO] 容器状态:
docker-compose ps

:: 显示连接信息
echo.
echo ========================================
echo [SUCCESS] 连接测试完成！
echo ========================================
echo.

echo [INFO] 数据库连接信息:
echo   PostgreSQL: postgresql://bicycle_user:bicycle123@localhost:5432/bicycle
echo   Redis: redis://localhost:6379
echo   MQTT:  mqtt://emqx:public@localhost:1883
echo.

echo [INFO] 管理界面:
echo   pgAdmin:         http://localhost:8080
echo   Redis Commander: http://localhost:8081
echo   EMQX Dashboard:  http://localhost:18083
echo.

echo [INFO] 测试用户账号:
echo   管理员: admin / admin123
echo   普通用户: testuser / admin123
echo.

echo 测试完成！按任意键退出...
pause >nul 